<template>
  <div class="top">
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
  import state from "../store/state";

  export default {
    name: "Login",
    data() {
      return {
        username: '',
        password: '',
      };
    },
    methods: {
      onSubmit(values) {
        // 发起请求
        this.$http({
          method: 'post',
          url: '/login',
          data: {
            username: values.username,
            password: values.password
          }

        }).then(resp => { // 这里使用箭头函数
          console.log(resp);

          if (resp.status == 200) {
            //成功
            var json = resp.data;
            if (json.msg == 'success') {
              sessionStorage.setItem('token', resp.data.token);
              state.username = values.username;
              this.$router.replace({path: '/my'});
            } else {

              alert(json.msg);
            }

          } else {
            //失败
            alert('登录失败2!', '失败!');
          }

        }, resp => {

          alert('找不到服务器⊙﹏⊙∥!', '失败!');
        })


      },
    },
  }
</script>

<style scoped>
  .top {

    margin: 180px auto;

    padding: 35px 35px 35px 35px;
  }
</style>
